﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace PhpDocBlockGenerator.Model.Threading
{
    public class WorkerHandler
    {
        private Thread _threadObserver;
        private Options _options;

        private bool _workDone = false;

        private List<IWorker> _workerThreads = new List<IWorker>();
        public List<IWorker> WorkerThreads
        {
            get { return _workerThreads; }
            set { _workerThreads = value; }
        }

        public delegate void WorkerThreadsEmptyEventHandler(object sender);
        public event WorkerThreadsEmptyEventHandler WorkerThreadsEmpty;

        public WorkerHandler(Options options)
        {
            _options = options;
            _threadObserver = new Thread(_observe);
            _threadObserver.Start();
        }

        public void Dispose()
        {
            _workDone = true;
            _threadObserver.Join();
        }

        private void _observe()
        {
            while (!_workDone)
            {
                if (WorkerThreads.Count == 0)
                {
                    _options.IsIdle = true;
                    if (_options.CurrentProgress > 0 && _options.CurrentProgress < 100)
                        _options.CurrentProgress = 100;
                    Thread.Sleep(5);
                }
                else
                {
                    _options.IsIdle = false;
                    IWorker workerThread = WorkerThreads.First();
                    workerThread.Thread.Join();
                    WorkerThreads.Remove(workerThread);
                    if (WorkerThreads.Count == 0)
                        WorkerThreadsEmpty(this);
                }
            }
        }
    }
}
